import { defineStore } from 'pinia'

const useDictStore = defineStore(
  'dict',
  {
    state: () => ({
      dict: []
    }),
    actions: {
      // 获取字典
      getDict(_key) {
        if (_key == null || _key == "") {
          return null;
        }
        try {
          for (let i = 0; i < this.dict.length; i++) {
            if (this.dict[i].key == _key) {
              return this.dict[i].value;
            }
          }
        } catch (e) {
          return null;
        }
        return null;
      },
      // 设置字典
      setDict(_key, value) {
        if (_key !== null && _key !== "") {
          // 检查是否已存在，如果存在则更新，否则添加
          const existingIndex = this.dict.findIndex(item => item.key === _key);
          if (existingIndex !== -1) {
            this.dict[existingIndex].value = value;
          } else {
            this.dict.push({
              key: _key,
              value: value
            });
          }
        }
      },
      // 删除字典
      removeDict(_key) {
        try {
          const index = this.dict.findIndex(item => item.key === _key);
          if (index !== -1) {
            this.dict.splice(index, 1);
            return true;
          }
        } catch (e) {
          return false;
        }
        return false;
      },
      // 清空字典
      cleanDict() {
        this.dict = [];
      },
      // 初始字典
      initDict() {
      }
    }
  })

export default useDictStore
